const fs = require("fs");
const path = require("path");
const stream = require("stream");
const { Readable, Writable, Transform } = stream;

// 读写流
// const readPath = path.resolve(__dirname, "../dist/1.txt");   // fs的流都是auto close的
// const writePath = path.resolve(__dirname, "../dist/2.txt");
// const frs = fs.createReadStream(readPath);
// const fws = fs.createWriteStream(writePath);
// frs.pipe(fws);
// frs.on("data", (data) => console.log(data.toString()));

// 自造读写流
const rs = new Readable({
  read(size) {
    // console.log("rs read:", size);
  },
});
rs.on("data", (chunk) => {
  //   console.log("rs data:", chunk.toString());
});
const ws = new Writable({
  write(chunk, encoding, callback) {
    console.log("ws chunk:", chunk.toString());
    callback();
  },
});
const ts = new Transform({
  transform(chunk, encoding, callback) {
    this.push(chunk.toString().toUpperCase());
    callback();
  },
});
rs.pipe(ts).pipe(ws);

//  pause后,继续push,但是不会触发data事件,resume后马上触发
async function run() {
  for (let i = 0; i < 10; i++) {
    // console.log(i, rs.isPaused());
    if (i === 1) {
      rs.pause();
    }
    await new Promise((r) => {
      setTimeout(() => {
        rs.push(i + "hey");
        r();
      }, 250);
    });

    if (i >= 9) {
      rs.resume();
    }
  }
}

run();
